package org.yzh.web.endpoint;

import com.ling5821.mtime.Mtime;
import io.github.yezhihao.netmc.session.Session;
import io.github.yezhihao.netmc.session.SessionListener;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.yzh.web.mapper.DeviceMapper;
import org.yzh.web.model.entity.DeviceDO;
import org.yzh.web.model.vo.DeviceInfo;
import org.yzh.web.model.vo.DeviceOnlineInfo;
import org.yzh.web.service.SessionService;
import org.yzh.web.service.VehicleTravelService;

import java.time.LocalDateTime;

@Slf4j
public class JTSessionListener implements SessionListener {

    @Autowired
    private DeviceMapper deviceMapper;

    @Autowired
    private VehicleTravelService vehicleTravelService;

    @Override
    public void sessionCreated(Session session) {
        log.info("设备上线 {}", session);
    }

    @Override
    public void sessionDestroyed(Session session) {
        DeviceInfo device = (DeviceInfo) session.getSubject();
        if (device != null) {
            log.info("设备下线 {} {}", session, device);
            LocalDateTime now = LocalDateTime.now();
            deviceMapper.update(new DeviceDO(device.getDeviceId(), false, now));
            /* 更新运行时间 */
            /* 拼装上线事件 Key */
            String key = device.getDeviceId() + ":" + device.getPlateNo() + DeviceOnlineInfo.SESSION_KEY;
            DeviceOnlineInfo onlineInfo = (DeviceOnlineInfo)session.getAttribute(key);
            if (onlineInfo == null) {
                return;
            }
            onlineInfo.setOfflineTime(Mtime.toEpochMilli(now));
            vehicleTravelService.updateTravelTime(onlineInfo);
        }
    }
}